package com.lv.utils.restartTask;

import com.lv.utils.mapper.CronMysqlMapper;
import com.lv.utils.utils.ScheduleTaskUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Component;

/**
 * @author: Lv_sc
 * Date:     2021/3/24 11:27
 * Description: //立即生效任务，只需要在改变数据时调用stop,start,restart控制即可
 * 1.缺点 多台机器部署的时候可能会出现执行多次的情况  解决方式：redis锁 未实现
 */
@Component
@Configuration
public class ConfigTask extends ScheduleTaskUtil {

    private static Logger logger = LoggerFactory.getLogger(ConfigTask.class);
    @Autowired
    private CronMysqlMapper mysqlMapper;

    @Override
    public void doSomething() {
        //调用接口服务
        logger.info("立即生效Cron正在运行==============");
    }

    @Override
    protected boolean getStatusIsAllClose() {
        int openNum = mysqlMapper.getStatusIsAllOpen();
        logger.info("配置服务开启数量为{}", openNum);
        if (openNum > 1) {
            logger.error("配置服务开启数量为{},数量大于1和设计不符，请检查数据", openNum);
        }
        return openNum == 0 ? true : false;
    }

    @Override
    protected String getCronExpression() {
        int openNum = mysqlMapper.getStatusIsAllOpen();
        String openConfigExpression = mysqlMapper.getOpenConfigExpression();
        if (openNum == 1 && CronSequenceGenerator.isValidExpression(openConfigExpression)) {
            return openConfigExpression;
        }
        logger.error("配置服务开启数量为{},表达式为{},启动默认Cron,每天零点执行一次", openNum,openConfigExpression);
        return "0 0 0 * * ?";
    }
}